package com.rc.web.listener;


import com.rc.common.annotate.WithoutTenant;
import com.rc.common.constant.CollectType;
import com.rc.common.constant.CommentType;
import com.rc.common.constant.OrderStatusType;
import com.rc.pojo.po.*;
import com.rc.web.converter.CollectConverter;
import com.rc.web.runner.SearchRunner;
import com.rc.web.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * 订单状态监听器
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class OrderStatusListener {
    private final OrderService orderService;
    private final ActivityService activityService;
    private final AdoptionService adoptionService;
    private final FarmService farmService;
    private final CommentService commentService;
    private final ConsumerService consumerService;
    private final CollectConverter collectConverter;
    private final CollectService collectService;
    private final SearchRunner searchRunner;

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = "order.expiration.queue"),
                    //设置延时交换机
                    exchange = @Exchange(value = "order.expiration.exchange",delayed = "true"),
                    //设置路由
                    key = {"order.expiration"}
            )
    })
    @WithoutTenant
    public void listenPaySuccess(Long id){
        log.info("设置订单过期：{}",id);
        Order order = orderService.getById(id);

        //确认订单状态没有被其他消费者更改
        if (order != null && order.getStatus() == OrderStatusType.UN_PAY){
            //设置订单状态关闭，设置关闭时间
            order.setStatus(OrderStatusType.CANCEL);
            order.setEndTime(LocalDateTime.now());
            orderService.updateById(order);
        }
    }

    /**
     * 监听用户发布评论 更新item的分数和推荐人数
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "comment.direct.queue"),
            exchange = @Exchange(name = "comment.direct"),
            key = {"update"}
    ))
    @WithoutTenant
    public void listenComment(Map<String,String> map) {
        Long itemId = Long.parseLong(map.get("itemId"));
        Integer type = Integer.parseInt(map.get("type"));

        Double score = commentService.getScore(itemId, type);
        Integer recommended = commentService.getRecommended(itemId, type);

        switch (type){
            case CommentType.FARM -> {
                Farm farm = Farm.builder().id(itemId).score(score).recommended(recommended).build();
                farmService.updateById(farm);
            }

            case CommentType.ACTIVITY -> {
                Activity activity = Activity.builder().id(itemId).score(score).recommended(recommended).build();
                activityService.updateById(activity);
            }

            case CommentType.ADOPTION -> {
                Adoption adoption = Adoption.builder().id(itemId).score(score).build();
                adoptionService.updateById(adoption);
            }
        }
    }

    /**
     * 监听用户更新信息 更新评论的昵称和头像
     * @param conId
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "user.direct.queue"),
            exchange = @Exchange(name = "user.direct"),
            key = {"update"}
    ))
    @WithoutTenant
    public void listenUserUpdate(Long conId){
        Consumer consumer = consumerService.getById(conId);

        Comment comment = Comment.builder()
                .conId(consumer.getId())
                .avatar(consumer.getAvatar())
                .nickName(consumer.getNickName())
                .build();

        commentService.updateByConId(comment);
    }


    /**
     * 商品信息更新
     * @param map
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "item.direct.queue"),
            exchange = @Exchange(name = "item.direct"),
            key = {"update"}
    ))
    @WithoutTenant
    public void listenItemUpdate(Map<String,String> map) throws Exception {
        Long itemId = Long.valueOf(map.get("itemId"));
        Integer type = Integer.valueOf(map.get("type"));

        Collect collect = switch (type){
            case CollectType.ACTIVITY -> {
                Activity activityServiceById = activityService.getById(itemId);
                yield collectConverter.activity2PO(activityServiceById);
            }

            case CollectType.ADOPTION -> {
                Adoption adoptionServiceById = adoptionService.getById(itemId);
                yield collectConverter.adoption2PO(adoptionServiceById);
            }

            case CollectType.FARM -> {
                Farm farmServiceById = farmService.getById(itemId);
                yield collectConverter.farm2PO(farmServiceById);
            }

            default -> throw new IllegalStateException("Unexpected value: " + type);
        };

        collectService.updateByItemIdAndType(collect);

        searchRunner.init();
    }
}
